﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using System;
using System.Collections.Generic;
using System.Net;

namespace ST.Buz.Web.Controllers
{
	[Route("partner")]
	public class PartnerController : MyBaseController
	{
		#region Ctor
		private readonly IServicePartner servicePartner;
		private readonly IServiceSysEnumCode serviceSysEnumCode;
		private VM_RelatedModule[] relatedModulesPartner;
		public PartnerController(
			IServicePartner _servicePartner,
			IServiceSysEnumCode _serviceSysEnumCode,
			ILogger<PartnerController> _logger) : base(_logger)
		{
			servicePartner = _servicePartner;
			serviceSysEnumCode = _serviceSysEnumCode;

			relatedModulesPartner = new VM_RelatedModule[]{
				new VM_RelatedModule(){
					id="sys_attachment",
					name="相关附件",
					count=0
				}
			};
		}
		#endregion

		#region Utilities

		protected List<SelectListItem> GetTypeOptions()
		{
			List<SelectListItem> lst = new List<SelectListItem>();
			lst.Add(new SelectListItem() { Value = ((int)PartnerType.布行).ToString(), Text = "布行" });
			lst.Add(new SelectListItem() { Value = ((int)PartnerType.供应商).ToString(), Text = "供应商" });
			lst.Add(new SelectListItem() { Value = ((int)PartnerType.供应商和客户).ToString(), Text = "客户/供应商" });
			return lst;
		}

		private VMS_IMS_Partner GetSearchModelFromJson(JObject paras)
		{
			var vm = new VMS_IMS_Partner
			{
				pnum = TextHelper.GetInt(paras, "pnum"),
				psize = TextHelper.GetInt(paras, "psize"),
				sortorder = TextHelper.GetString(paras, "sortorder"),

				name = TextHelper.GetString(paras, "name"),
				code = TextHelper.GetString(paras, "code"),
				pycode = TextHelper.GetString(paras, "pycode"),
				phone = TextHelper.GetString(paras, "phone"),
				contactman = TextHelper.GetString(paras, "contactman"),
				contactphone = TextHelper.GetString(paras, "contactphone"),
				catid = TextHelper.GetInts(paras, "catid"),
				type = TextHelper.GetInts(paras, "type"),
				ids = TextHelper.GetInts(paras, "ids")
			};
			return vm;
		}

		#endregion

		public IActionResult Index()
		{
			return RedirectToAction("List");
		}


		[ValidateSession]
		[HttpPost("autocomplete")]
		public IActionResult Autocomplete([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int type = TextHelper.GetInt(paras, "type", (int)PartnerType.布行);
				string name = TextHelper.GetString(paras, "name");
				string pycode = TextHelper.GetString(paras, "pycode");
				string phone = TextHelper.GetString(paras, "phone");
				string keyword = TextHelper.GetString(paras, "query");
				int maxShow = TextHelper.GetInt(paras, "limit", 100);
				//bool includeGroup = TextHelper.GetString(paras, "group") == "1";

				var result = new List<object>();
				//if (includeGroup)
				//{
				//	var groups = serviceGroup.Query(keyword, sessionCurrent, maxShow);
				//	result.AddRange(groups);
				//}
				result.AddRange(servicePartner.Query(type, name, pycode, phone, keyword, sessionCurrent, maxShow));

				JsonSerializerSettings settings = new JsonSerializerSettings
				{
					DateFormatString = "yyyy-MM-dd HH:mm:ss"
				};
				return new JsonResult(new { r = true, code = 200, suggestions = result }, settings);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResult(new { suggestions = new List<VM_ProdSkuLookup>() });
			}
		}

		[ValidateSession]
		[HttpGet("list")]
		public IActionResult List()
		{
			try
			{
				var sessionCurrent = GetSessionFromRequest();
				ViewBag.ServiceCode = "6B6C6C0359";
				var enumCode = serviceSysEnumCode.EnsureCodeValid("IMS_PartnerCat", "往来单位分类", sessionCurrent);
				ViewBag.PartnerCatEnumID = enumCode.ID;
				ViewBag.PartnerCatEnumCode = enumCode.Code;
				ViewBag.PartnerCatEnumName = enumCode.Name;
				ViewBag.OrgID = sessionCurrent.OrgID;
				ViewBag.TypeOptions = GetTypeOptions();
				ViewBag.StateOptions = GetEnums(typeof(PartnerState));
				return View();
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开往来单位列表页面出错");
				ViewBag.ErrorMsg = "打开往来单位列表页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpGet("mlist")]
		public IActionResult MobileList()
		{
			try
			{
				var sessionCurrent = GetSessionFromRequest();
				ViewBag.ServiceCode = "6B6C6C0359";
				var enumCode = serviceSysEnumCode.EnsureCodeValid("IMS_PartnerCat", "往来单位分类", sessionCurrent);
				ViewBag.PartnerCatEnumID = enumCode.ID;
				ViewBag.PartnerCatEnumCode = enumCode.Code;
				ViewBag.PartnerCatEnumName = enumCode.Name;
				ViewBag.OrgID = sessionCurrent.OrgID;
				ViewBag.TypeOptions = GetTypeOptions();
				ViewBag.StateOptions = GetEnums(typeof(PartnerState));
				return View();
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开往来单位列表页面出错");
				ViewBag.ErrorMsg = "打开往来单位列表页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpPost("search")]
		public IActionResult Search([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				if (searchModel.type == null || searchModel.type.Length == 0)
				{
					searchModel.type = new int[] { (int)PartnerType.供应商, (int)PartnerType.布行, (int)PartnerType.供应商和客户 };
				}
				else if (searchModel.type.Length == 1)
				{
					switch (searchModel.type[0])
					{
						case (int)PartnerType.供应商:
							searchModel.type = new int[] { (int)PartnerType.供应商, (int)PartnerType.供应商和客户 };
							break;
						case (int)PartnerType.布行:
							searchModel.type = new int[] { (int)PartnerType.布行, (int)PartnerType.供应商和客户 };
							break;
					}
				}
				if (sessionCurrent.OrgID > 0)
				{
					searchModel.orgids = new int[] { sessionCurrent.OrgID };
				}
				PageData pageData = servicePartner.GetPageList(searchModel, sessionCurrent);
				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("add")]
		public IActionResult Add()
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				ViewBag.ServiceCode = "6B6C6C0359";
				ViewBag.RelatedModules = relatedModulesPartner;
				var enumCode = serviceSysEnumCode.GetByCode("IMS_PartnerCat", sessionCurrent);
				ViewBag.PartnerCatEnumID = enumCode.ID;
				var vm = new IMS_Partner()
				{
					Type = (int)PartnerType.布行
				};
				return View("Edit", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开新增页面出错");
				return new JsonResultBase(false, "打开新增页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("madd")]
		public IActionResult MobileAdd()
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				ViewBag.ServiceCode = "6B6C6C0359";
				ViewBag.RelatedModules = relatedModulesPartner;
				var enumCode = serviceSysEnumCode.GetByCode("IMS_PartnerCat", sessionCurrent);
				ViewBag.PartnerCatEnumID = enumCode.ID;
				var vm = new IMS_Partner()
				{
					Type = (int)PartnerType.布行
				};
				return View("MobileEdit", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开新增页面出错");
				return new JsonResultBase(false, "打开新增页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("edit/{id}")]
		[HttpGet("edit")]
		public IActionResult Edit(string id)
		{
			ViewBag.ServiceCode = "6B6C6C0359";
			ViewBag.RelatedModules = relatedModulesPartner;
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				int rowID = TextHelper.GetInt(id);
				var vm = servicePartner.GetEditDetail(rowID, sessionCurrent);
				var enumCode = serviceSysEnumCode.GetByCode("IMS_PartnerCat", sessionCurrent);
				ViewBag.PartnerCatEnumID = enumCode.ID;
				return View(vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				return new JsonResultBase(false, "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("medit/{id}")]
		[HttpGet("medit")]
		public IActionResult MobileEdit(string id)
		{
			ViewBag.ServiceCode = "6B6C6C0359";
			ViewBag.RelatedModules = relatedModulesPartner;
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				int rowID = TextHelper.GetInt(id);
				var vm = servicePartner.GetEditDetail(rowID, sessionCurrent);
				var enumCode = serviceSysEnumCode.GetByCode("IMS_PartnerCat", sessionCurrent);
				ViewBag.PartnerCatEnumID = enumCode.ID;
				return View(vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				return new JsonResultBase(false, "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("save")]
		public IActionResult Save([FromBody] IMS_Partner vm)
		{
			try
			{
				CheckParams();
				UserSession sessionCurrent = GetSessionFromRequest();
				int rowID = servicePartner.AddOrUpdate(vm, sessionCurrent);
				return new JsonResultBase(rowID);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "新增失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("view/{id}")]
		[HttpGet("view")]
		public IActionResult ViewDetail(string id)
		{
			ViewBag.ServiceCode = "6B6C6C0359";
			ViewBag.RelatedModules = relatedModulesPartner;
			try
			{
				int rowID = TextHelper.GetInt(id);
				UserSession sessionCurrent = GetSessionFromRequest();
				var vm = servicePartner.GetViewDetail(rowID, sessionCurrent);

				return View("View", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("mview/{id}")]
		[HttpGet("mview")]
		public IActionResult MobileViewDetail(string id)
		{
			ViewBag.ServiceCode = "6B6C6C0359";
			ViewBag.RelatedModules = relatedModulesPartner;
			try
			{
				int rowID = TextHelper.GetInt(id);
				UserSession sessionCurrent = GetSessionFromRequest();
				var vm = servicePartner.GetViewDetail(rowID, sessionCurrent);

				return View("MobileView", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("delete")]
		public IActionResult Delete([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var rowID = TextHelper.GetInt(paras, "id");
				var result = servicePartner.Delete(rowID, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("batchdelete")]
		public IActionResult BatchDelete([FromBody] int[] ids)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				var result = servicePartner.BatchDelete(ids, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("gencode")]
		public IActionResult GenCode([FromBody] JObject paras)
		{
			try
			{
				CheckParams();
				var catID = TextHelper.GetInt(paras, "catid");
				UserSession sessionCurrent = GetSessionFromRequest();
				var code = servicePartner.GenCode(catID, sessionCurrent);
				return new JsonResultBase(code);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "生成编号失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("export")]
		public IActionResult Export(JObject obj)
		{
			throw new NotImplementedException();
		}
	}
}
